<template>
  <div class="search-container">
    <!-- 搜索卡片容器 -->
    <el-card class="search-card" shadow="hover">
      <!-- 搜索表单 -->
      <el-form
          :inline="true"
          :model="searchForm"
          class="search-form"
          ref="searchForm"
      >
        <!-- 用户名搜索项 -->
        <el-form-item label="用户名">
          <el-input
              size="small"
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
              class="search-input"
          ></el-input>
        </el-form-item>

        <!-- 性别搜索项 -->
        <el-form-item label="性别">
          <el-select
              size="small"
              v-model="searchForm.gender"
              placeholder="请选择性别"
              clearable
              class="search-select"
          >
            <el-option label="F" value="1"></el-option>
            <el-option label="M" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
              style="width: 470px"
              v-model="searchForm.date"
              value-format="yyyy-MM-DD"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <!-- 操作按钮组 -->
        <el-form-item class="form-actions">
          <el-button
              type="primary"
              size="small"
              @click="OnSearch"
              :loading="loading"
          >
            查询
          </el-button>
          <el-button
              type="text"
              size="small"
              @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 下方表格区域-->
    <el-card class="table-card" shadow="hover">
      <!-- 批量删除按钮 -->
      <el-button  type="danger" size="small" @click="deleteBatch">批量删除</el-button>
      <!-- 添加按钮 -->
      <el-button  type="success" size="small" @click="openDialog">添加</el-button>
      <el-table
          :data="tableData"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            fixed
            prop="register_time"
            label="注册时间"
            width="270">
        </el-table-column>
        <el-table-column
            fixed
            prop="id"
            label="编号"
            width="80">
        </el-table-column>
        <el-table-column
            prop="avatar"
            label="头像"
            width="120">
          <template slot-scope="scope">
            <div class="block"><el-avatar :size="50" :src="scope.row.avatar"></el-avatar></div>
          </template>
        </el-table-column>
        <el-table-column
            prop="username"
            label="姓名"
            width="120">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="电话"
            width="170">
        </el-table-column>
        <el-table-column
            prop="gender"
            label="性别"
            width="120">
        </el-table-column>
        <el-table-column
            prop="password"
            label="密码"
            width="150">
        </el-table-column>
        <el-table-column
            prop="balance"
            label="余额"
            width="120">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="block">
        <span class="demonstration">完整功能</span>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageinfo.pageNum"
            :page-sizes="[3, 6, 10, 20]"
            :page-size="pageinfo.pages"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageinfo.total">
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加更新用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="userDiglogVisible">
      <el-form
          :inline="true"
          :model="userForm"
          class="search-form"
          ref="searchForm"
      >
        <el-form-item label="用户名">
          <el-input
              size="small"
              v-model="userForm.username"
              placeholder="请输入用户名"
              clearable
              class="search-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
              size="small"
              v-model="userForm.password"
              placeholder="请输入密码"
              clearable
              class="search-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select
              size="small"
              v-model="userForm.gender"
              placeholder="请选择性别"
              clearable
              class="search-select"
          >
            <el-option label="F" value="1"></el-option>
            <el-option label="M" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-button
            type="text"
            size="small"
            @click="handleAdd"
        >
          提交
        </el-button>
        <el-button
            type="text"
            size="small"
            @click="handleReset"
        >
          重置
        </el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {findUser, delBatch, addUser} from '@/api/user'
export default {
  name: "UserSearchForm",
  data() {
    return {
      //日期快捷组件
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 分页+搜索表单数据模型
      searchForm: {
        username: "",  // 用户名
        gender: null,       // 性别
        date: [],
        beginDate: null,
        endDate: null,
        pageNum: 1,
        pageSize: 3
      },
      //表格数据
      tableData: [],
      //分页数据
      pageinfo: {
        pasgeNum: 1,
        total: null,
        pageSize: 3,
        pages: null
      },
      ids: [],
      dialogTitle: "添加用户",
      //对话框状态
      userDiglogVisible: false,
      userForm: {},
      // 加载状态
      loading: false
    };
  },
  computed:{
    delDisable(){
      if(this.ids.length !== 0){
        return  true
      }else {
        return  false
      }

    }
  },
  //生命周期函数
  created() {
    this.fetchData(this.searchForm)
  },
  methods: {
    //获取用户数据
    fetchData(){
      // console.log("获取用户数据")
      //发请求
      findUser(this.searchForm).then(res => {
      if(res.code !== 200){
        this.$message.warning(res.msg)
        this.tableData = []
      }else {
        this.$message.success("查询数据成功")
        this.tableData = res.data.list
        this.pageinfo.pageSize = res.data.pageSize
        this.pageinfo.pageTotal = res.data.pageTotal
        this.pageinfo.total = res.data.total
        this.pageinfo.pages = res.data.pages
      }
      })
    },
    /**
     * 处理搜索逻辑
     */
    OnSearch(){
      // console.log("搜索都关键词",this.searchForm)
      this.searchForm.beginDate = this.searchForm.date[0]
      this.searchForm.endDate = this.searchForm.date[1]
      console.log("搜索都关键词",this.searchForm)
      this.fetchData();
    },

    /**
     * 重置表单
     */
    handleReset() {
      this.searchForm = {
        username: "",
        sex: ""
      };
      // 重置表单校验状态
      this.$refs.searchForm.resetFields();
    },
    //复选框改变
    handleSelectionChange(val) {
      console.log("选中的行数",val)
      this.ids = []
      this.delDisable = false
      val.map(item => {
        this.ids.push(item.id)
      })
      if (this.ids.length === 0) {
        this.delDisable = true
      }else {
        this.delDisable = false
      }
    },
    //处理更新
    handleEdit(index, row) {
      console.log(index, row);
    },
    //处理删除
    handleDelete(index, row) {
      console.log(index, row);
      this.dialogTitle = "更新用户"
      this.userDiglogVisible = true
    },
    //页面大小改变触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.pageSize = val
      this.fetchData()
    },
    //页码改变触发  跳转
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.pageNum = val
      this.fetchData()
    },
    deleteBatch(){
      console.log("批量删除")
      console.log("批量删除的id",this.ids.length)
      if (!this.ids.length){
        this.$message.error("没有选择任何数据删除")
        return
      }else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         //发请求删除
          delBatch({ids:this.ids.join( ",")}).then(res => {
            console.log("批量删除结果",res)
            if (res.code !== 200){
              this.$message.error(res.msg)
            }else {
              this.$message.success(res.msg)
              this.searchForm.pageNum = 1
              this.fetchData()
            }
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        });
      }
    },
    openDialog(){
      this.dialogTitle = "添加用户"
      this.userDiglogVisible = true
    },
    //添加用户
    handleAdd(){
      if (this.dialogTitle==="添加用户"){
        console.log("添加用户",this.userForm)
        addUser(this.userForm).then(res => {
          if (res.code !== 200){
            this.$message.error(res.msg)
          }else {
            this.$message.success(res.msg)
            this.searchForm.pageNum = 1
            this.fetchData()
          }
          this.userDiglogVisible = false
        }

      )
    }else {
        console.log("更新用户",this.userForm)
      }
    }

  }
};
</script>

<style scoped>
/* 容器样式 */
.search-container {
  padding: 2px;
}

/* 搜索卡片样式 - 增加最大宽度使卡片更长 */
.search-card {
  width: 1600px;
  margin: 0 auto;
  padding: 15px 20px;
  box-sizing: border-box;
}

/* 表单样式 */
.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

/* 表单项样式 */
.el-form-item {
  margin-right: 20px !important; /* 增加表单项间距 */
  margin-bottom: 0 !important;
}

/* 输入框样式 - 相应增加宽度 */
.search-input {
  width: 280px;
}

/* 选择框样式 - 相应增加宽度 */
.search-select {
  width: 180px;
}

/* 按钮组样式 */
.form-actions {
  margin-left: 15px !important;
}

/* 按钮间距 */
.el-form-item .el-button + .el-button {
  margin-left: 8px;
}
.table-card {
  border-radius: 10px;
  margin-radius: 10px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .search-input, .search-select {
    width: 100%;
  }

  .el-form-item {
    width: 100%;
    margin-right: 0 !important;
    margin-bottom: 10px !important;
  }

  .form-actions {
    margin-left: 0 !important;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
